package ml.kupin.controller;

import com.alibaba.fastjson.JSON;
import ml.kupin.common.utils.FastDfsClientUtils;
import ml.kupin.common.vo.KindEditorFileUploadResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by 小柯(Allen Kerr) on 17.4.25 20:32.
 */
@Controller
@RequestMapping("/pic")
public class PictureController {

    @Value("${image_server_address}")
    private String image_server_address;

    /**
     * org.springframework.http.MediaType类
     * public final static String TEXT_PLAIN_VALUE = "text/plain";
     */
    @RequestMapping(value = "/upload", produces = MediaType.TEXT_PLAIN_VALUE + ";charset=utf-8")
    @ResponseBody   //直接返回json字符串，但是该注解不能删，否则就是页面跳转了
    public String uploadFile(MultipartFile uploadFile) {
        KindEditorFileUploadResult uploadResult = null;
        try {
            FastDfsClientUtils fastDfsClientUtils = new FastDfsClientUtils("classpath:config/fastdfs.conf");
            //取文件扩展名
            String originalFilename = uploadFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //把图片上传的图片服务器，得到一个图片的地址
            String fileUrl = fastDfsClientUtils.uploadFile(uploadFile.getBytes(), extName);
            //补充为完整的url
            String url = image_server_address + fileUrl;
            //上传成功
            uploadResult = new KindEditorFileUploadResult(0, url);
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            uploadResult = new KindEditorFileUploadResult("图片上传失败！！！", 1);
        }
        //返回结果
        //直接用@ResponseBody返回对象，浏览器兼容性不佳
        //return uploadResult;
        return JSON.toJSONString(uploadResult);
    }

}
